// pages/select_role/select_role.js
var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    bar_height: 0,
    role_num: 0,
    // card_w: 103.5,
    card_w: 82.8,
    card_list:[]
    
  },
  touch_role:function(e) {
    // let flag = false;
    // let token = app.globalData.globalToken
    // console.log("获取到的token:", token)
    // if(token) flag = true
    // if(!flag) {
    //   console.log("暂无权限")
    //   return;
    // }
    // console.log(e)
    let tar = this.data.card_list[e.currentTarget.dataset.targetid]
    let property = this.solveProperty(tar.property)
    this.setData({
      tar_id: e.currentTarget.dataset.targetid,
      tar_src: tar.card_src,
      tar_desc: tar.card_desc,
      tar_selected: tar.card_selected,
      tar_role: tar.card_role,
      tar_property: property,
      show_tar: true
    })
  },
  solveProperty: function(e) {
    if(e == 1) return "好人阵营"
    else if(e == 2) return "狼人阵营"
    else return "未知阵营"
  },
  tar_event: function(e) {
    console.log(e)
  },
  cut: function(e) {
    this.setData({
      role_num: this.data.role_num - 1
    })
  },
  add: function(e) {
    this.setData({
      role_num: this.data.role_num + 1
    })
  },
  select: function(e) {
    // 更新选择数量
    // console.log(e)
    let todo = 'card_list[' + this.data.tar_id + '].card_selected'
    this.setData({
      // [selected_list[this.data.tar_id]]: e.detail.val
      [todo]: e.detail.val
    })
  },
  romove: function(e) {
    wx.removeStorage({
      key: 'token',
      success:function(e) {
        console.log(e)
      },
      fail: function(e) {
        console.error(e)
      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let _this = this
    wx.getSystemInfo({
      success: function (res) {
        // console.log(res)
        _this.setData({
          card_w: res.screenWidth / 6
        })
        // 判断设备是否为刘海屏
        if (res.model.indexOf("iPhone") >= 0 || (res.statusBarHeight > 20)) {
          _this.setData({
            bar_height: res.statusBarHeight,
          })
        }
      }
    })
    // 获取卡片集合
    wx.request({
      url: 'http://localhost:8080/card/list',
      success: function(res) {
        _this.setData({
          card_list: res.data.data.list
        })
      }, fail(){
        wx.showToast({
          title: '服务器正在维护',
          icon: "error"
        })
      }
    })
    
    // 异步
    wx.getStorage({
      key: "token",
      success: function(e) {
        console.log("获取token成功")
        console.log(e)
        if(e.data) {
          wx.request({
            url: `http://localhost:8080/user/check_auth?token=${e.data}`,
            success:function(res) {
              // console.log(res)
              // token有效
              if(res.data.res == 200) {
                console.log("检验token成功")
                // 更新token
                wx.request({
                  url: `http://localhost:8080/user/refresh_auth?token=${e.data}`,
                  success: function(refresh) {
                    // 更新成功保存到缓存
                    if(refresh.data.res == 200) {
                      console.log("更新token成功")
                      console.log(refresh)
                      wx.setStorageSync({
                        key: 'token',
                        value: refresh.data.data.token
                      })
                      
                      app.globalData.globalToken = refresh.data.data.token
                      console.log("全局变量globalToken:" ,app.globalData.globalToken)
                    }
  
                    // 更新失败销毁token
                     else {
                      console.error("token已过期")
                      wx.removeStorage({
                        key: 'token',
                      })
                    }
                  }, 
                  fail: function(refresh) {
                    console.error(refresh)
                    wx.removeStorage({
                      key: 'token',
                    })
                    wx.showToast({
                      title: '网络异常',
                    })
                  }
                })
              }
              // token过期
               else if(res.data.res == 401) {
                 console.log("token过期需要重新登录")
                wx.removeStorage({
                  key: 'token',
                })
              } else {
                console.error("未知错误")
                wx.removeStorage({
                  key: 'token',
                })
                console.log(res)
              }
            },
            fail: function(res) {
              console.error(res)
              wx.removeStorage({
                key: 'token',
              })
            },
          })
        } else {
          console.log("token存在问题！", e)
          wx.removeStorage({
            key: 'token',
          })
        }
      },

      fail: function(e) {
        console.log("本地没有token")
      }
    })
    
  },
  timeInDate() {
    let now = Date.now()
    let old = wx.getStorageSync('old') + 259200000
    return old && now < old;
  },
  getUserInfo: function(e) {
    console.log(e)
  },
  start_up: function(res) {
    let _this = this
      if(!app.globalData.globalToken) {
        wx.showLoading({
          title: '正在登录',
        })
        wx.login({
          // timeout: 1000,
          success(res) {
            console.log(res)
            if(res.code) {
              wx.request({
                // ?code=${res.code}
                url: `http://localhost:8080/user/check_code?code=${res.code}`,
                success:function(res) {
                  console.log(res)
                  if(res.data.res == 200 && res.data.data.token) {
                    wx.setStorage({
                      key: "token",
                      data: res.data.data.token,
                      success: function(e) {
                        wx.hideLoading()
                        console.log("设置缓存成功")
                        app.globalData.globalToken = res.data.data.token
                        wx.request({
                          url: 'http://localhost:8080/room/create',
                          method: "POST",
                          data: {
                            token: app.globalData.globalToken,
                            card_list: card_list
                          },
                          success: function(res) {
                            console.log(res)
                            wx.showToast({
                              title: '游戏马上开始！',
                              icon: "success"
                            })
                          },
                          fail: function(res) {
                            console.log(res)
                            wx.showToast({
                              title: '服务器繁忙！',
                              icon: "error"
                            })
                          }
                        })
                      }
                    })
                  } else {
                    wx.hideLoading()
                    wx.showToast({
                      title: res.data.msg,
                      icon: 'error'
                    })
                  }
                },
                fail: function(res) {
                  wx.hideLoading()
                  wx.showToast({
                    title: '网络异常，请重试',
                    icon: 'error'
                  })
                  console.log(res)
                }
              })
            } else {
              wx.hideLoading()
              wx.showToast({
                title: '网络异常，请重试',
                icon: 'error'
              })
              console.log("login failed")
            }
          },
          fail(res) {
            wx.showToast({
              title: '网络异常，请重试',
              icon: 'error'
            })
            console.error("login failed")
            console.log(res)
          }
        })
      } else {
        wx.request({
          url: 'http://localhost:8080/room/create',
          method: "POST",
          data: {
            token: app.globalData.globalToken,
            card_list: _this.data.card_list
          },
          success: function(res) {
            console.log(res)
            wx.showToast({
              title: '游戏马上开始！',
              icon: "success"
            })
          },
          fail: function(res) {
            console.log(res)
            wx.showToast({
              title: '服务器繁忙！',
              icon: "error"
            })
          }
        })
      }
    
  },
  create_room: function(e) {
    let num = 0;
    for(let i = 0; i < this.data.card_list.length; i ++) {
      num += this.data.card_list[i].card_selected;
    }
    if(num == 0) {
      wx.showToast({
        title: '请先选择角色',
        icon: "none"
      })
      return;
    } else if(num < 6) {
      wx.showToast({
        title: '需大于6人才能开始游戏',
        icon: "none"
      })
      return;
    }
    let _this = this
      if(!app.globalData.globalToken) {
        wx.getUserProfile({
          desc: "在交互中展示头像区分用户",
          success: function(info) {
            console.log(info)
            wx.showLoading({
              title: '正在登录',
            })
            wx.login({
              // timeout: 1000,
              success(res) {
                console.log(res)
                if(res.code) {
                  wx.request({
                    // ?code=${res.code}
                    url: `http://localhost:8080/user/login_with_info`,
                    method: "POST",
                    data: {
                      code: res.code,
                      user_info: info.userInfo
                    },
                    success:function(res) {
                      console.log(res)
                      if(res.data.res == 200 && res.data.data.token) {
                        wx.setStorage({
                          key: "token",
                          data: res.data.data.token,
                          success: function(e) {
                            console.log("设置缓存成功")
                            app.globalData.globalToken = res.data.data.token
                            wx.showLoading({
                              title: '正在创建房间',
                            })
                            wx.request({
                              url: 'http://localhost:8080/room/create',
                              method: "POST",
                              data: {
                                token: app.globalData.globalToken,
                                card_list: _this.data.card_list
                              },
                              success: function(res) {
                                console.log(res)
                                let result = res.data
                                if(result.res == 10003) {
                                  wx.showToast({
                                    title: '游戏马上开始！',
                                    icon: "success"
                                  })
                                  wx.navigateTo({
                                    url: `../main/main?room_id=${result.data.room_id}`,
                                  })
                                } else {
                                  wx.showToast({
                                    title: '房间创建失败，请重新启动小程序',
                                    icon: "none"
                                  })
                                }
                              },
                              fail: function(res) {
                                console.log(res)
                                wx.showToast({
                                  title: '服务器繁忙！',
                                  icon: "error"
                                })
                              }
                            })
                          }
                        })
                      } else {
                        wx.hideLoading()
                        wx.showToast({
                          title: res.data.msg,
                          icon: 'error'
                        })
                      }
                    },
                    fail: function(res) {
                      wx.hideLoading()
                      wx.showToast({
                        title: '网络异常，请重试',
                        icon: 'error'
                      })
                      console.log(res)
                    }
                  })
                } else {
                  wx.hideLoading()
                  wx.showToast({
                    title: '网络异常，请重试',
                    icon: 'error'
                  })
                  console.log("login failed")
                }
              },
              fail(res) {
                wx.hideLoading()
                console.error("login failed")
                console.log(res)
              }
            })
          }
        })
      } else {
        wx.request({
          url: 'http://localhost:8080/room/create',
          method: "POST",
          data: {
            token: app.globalData.globalToken,
            card_list: this.data.card_list
          },
          success: function(res) {
            console.log(res)
            let result = res.data
            if(result.res == 10003) {
              wx.showToast({
                title: '游戏马上开始！',
                icon: "success"
              })
              wx.navigateTo({
                url: `../main/main?room_id=${result.data.room_id}`,
              })
            } else {
              wx.showToast({
                title: '房间创建失败，请重新启动小程序',
                icon: "none"
              })
            }
          },
          fail: function(res) {
            console.log(res)
            wx.showToast({
              title: '服务器繁忙！',
              icon: "error"
            })
          }
        })
      }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})